package com.ruoyi.classai.service.impl;

import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.classai.config.DeepSeekConfig;
import com.ruoyi.classai.domain.AnalysisModeRel;
import com.ruoyi.classai.service.IEwcDeepSeekAccessService;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

@Service
public class EwcDeepSeekAccessServiceImpl implements IEwcDeepSeekAccessService {
    private static final Logger log = LoggerFactory.getLogger(EwcDeepSeekAccessServiceImpl.class);
    @Autowired
    private DeepSeekConfig deepSeekConfig;

    @Override
    public String deepSeekAccessRec(AnalysisModeRel analysisModeRel) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(30, TimeUnit.SECONDS) // 连接超时时间
                .readTimeout(30, TimeUnit.SECONDS)    // 读取超时时间
                .writeTimeout(30, TimeUnit.SECONDS)   // 写入超时时间
                .build();
//        MediaType mediaType = MediaType.parse("application/json");
        String requestBody = "{\"model\": \"deepseek-reasoner\",\"messages\": [{\"role\": \"user\", \"content\": \"你好\"}], \"stream\": false}";
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), requestBody);
        Request request = new Request.Builder()
//                .url(deepSeekConfig.getApiUrl())
                .url("https://api.deepseek.com/v1/chat/completions")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer sk-e21b4920ac804681befbcdb6d213dfc7")
                .build()
                ;
        Response response = client.newCall(request).execute();
          log.info(response.body().string());

        StringBuilder result = new StringBuilder();
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                return null;
            }

            // 流式读取分块数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody.byteStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("data: ")) {
                    String chunk = line.substring(6);
                    if (chunk.equals("[DONE]")) {
                        break; // 终止信号
                    }
                    // 解析JSON分块并提取内容
                    result.append(parseChunkContent(chunk));
                }
            }

        return result.toString();
    }

    private String parseChunkContent(String chunk) {

        return chunk;
    }
}
